package com.example.leetcode.trainingcamp.week2.practice;

public class Test19 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null){
            return null;
        }
        int count = 0; //得到总长度
        ListNode pre = head;
        while (pre != null){
            count++;
            pre = pre.next;
        }
        if (count == n){
            return head.next;
        }else if (count < n){
            return head;
        }else {
            pre = head;
            int t = 1;
            while (t<count-n){
                pre = pre.next;
                t++;
            }
            pre.next = pre.next.next;
            return head;
        }
    }
}


class Demo19{
  public static void main(String[] args) {
    Test19 t = new Test19();
    ListNode head = new ListNode(1);
    head.next = new ListNode(2);
    head.next.next = new ListNode(3);
    head.next.next.next = new ListNode(4);
    head.next.next.next.next = new ListNode(5);
    ListNode node = t.removeNthFromEnd(head, 2);
    while (node != null){
      System.out.println("val="+node.val);
      node = node.next;
    }
  }
}